<template>
    <modal-view :title="title" :loading="progressLoading" :percent="percent" :tip="tip" @close="showModal = false" @save="handleSave" v-if="showModal">
        <div class="page-wrap" v-loading="loading">
            <div class="page-cont" v-if="detailData.id" id="pdfDom">
                <template v-for="(item, index) of comps" :key="index">
                    <div v-if="item.show">
                        <a-divider style="margin: 0" v-if="index !== 0" />
                        <component :ref="setCompsItemRef(item)" :is="item.comName" :detail="detailData" :disabled="item.disabled" :stepStatus="processStepStatus" @success="getDetailData" @detailChange="detailChange" />
                    </div>
                </template>
            </div>
        </div>
    </modal-view>
</template>

<script lang="ts">
import BaseInfo from '@/views/version/versionDetailPreview/components/BaseInfo.vue';
import RelateFile from '@/views/version/versionDetailReview/components/RelateFile/index.vue';
import RelateRequireList from './components/RelateRequire/relateRequireList.vue';
import RelateProductList from './components/RelateRequire/relateProductList.vue';
import RelateJiraRequireList from './components/RelateRequire/RelateJIraIssue/index.vue';
import ProductAudit from './components/ProductAudit.vue';
import ModalView from './ModalView.vue';
import { message } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import { dataURLtoFile } from '@/utils/file/file';
import api from '@/api';
import store from '@/store';
import filters from '@/utils/filter';
import { FileItem } from '@/types';
import { stepStatusConnectType } from '@/config/commonData';
import { defineComponent, unref, reactive, toRefs, computed, getCurrentInstance, onBeforeUnmount } from 'vue';
export default defineComponent({
    name: 'VersionDetail',
    components: {
        BaseInfo,
        RelateFile,
        RelateRequireList,
        RelateProductList,
        ProductAudit,
        RelateJiraRequireList,
        ModalView
    },
    emits: ['success'],
    setup(_, { emit }) {
        const allComps = [{ comName: 'BaseInfo' }, { comName: 'RelateRequireList' }, { comName: 'RelateProductList' }, { comName: 'RelateJiraRequireList' }, { comName: 'RelateFile' }, { comName: 'ProductAudit' }];
        const route = useRoute();
        const instance: any = getCurrentInstance();
        const compsItemRefs: any = reactive({});
        const state = reactive<any>({
            form: {},
            processStepStatus: '', //对应流程类型下的某个节点
            loading: false,
            detailData: {},
            comps: [],
            showModal: false,
            title: '',
            progressLoading: false,
            percent: 0,
            tip: ''
        });
        const empId = computed(() => {
            return store.getters.userInfo.employeeDTO.empId;
        });
        const setCompsItemRef = (item) => (el) => {
            compsItemRefs[item.comName] = el;
        };
        const getDetailData = async () => {
            state.loading = true;
            const query = {
                id: route.query.id
            };
            const { success, moule, errorMsg } = await api.versionModel.findById(query);
            if (success) {
                state.detailData = { ...moule };
                // 进行中,才获取历史记录
                if (!state.detailData.replenishRecord) {
                    // 进行中调流程节点
                    if (state.detailData.status === '2') {
                        await getProcessStatus();
                    }
                }
                let { expectTime, versionName } = state.detailData;
                versionName = versionName.length >= 30 ? versionName.slice(0, 30) + '...' : versionName;
                state.title = `${filters.dateFilter(expectTime)} 产品版本评审记录表—${versionName}`;
            } else {
                message.error(errorMsg);
            }
            state.loading = false;
            initComps();
        };
        const getProcessStatus = async () => {
            const query = {
                instanceId: state.detailData.instanceId
            };
            const { success, moule } = await api.productProcessModel.processStatus(query);
            if (success) {
                state.processStepStatus = moule;
            }
        };
        const detailChange = (data: Recordable) => {
            state.detailData = {
                ...state.detailData,
                ...data
            };
        };
        // 动态判断模块是否显示
        const checkIsShow = (name: string) => {
            // 业务需求模块
            if (name === 'RelateRequireList') {
                const { pmpRequestInfos } = state.detailData;
                const res = pmpRequestInfos ? pmpRequestInfos.length : false;
                return res;
            }
            // 产品需求模块
            if (name === 'RelateProductList') {
                const { pmpProductRequires } = state.detailData;
                let res = true;
                if (pmpProductRequires) {
                    res = pmpProductRequires.length ? !!pmpProductRequires.filter((item) => !item.relateRequireId).length : false;
                } else {
                    res = false;
                }
                return res;
            }
            // jiraIssue
            if (name === 'RelateJiraRequireList') {
                const { pmpJiraIssueDTOs } = state.detailData;
                const res = pmpJiraIssueDTOs ? pmpJiraIssueDTOs.length : false;
                return res;
            }
            return true;
        };
        // 动态判断模块是否可编辑
        const checkIsDisabled = (name: string) => {
            return name === 'BaseInfo' ? true : false;
        };
        const open = () => {
            state.detailData = {};
            state.showModal = true;
            init();
        };
        const initComps = () => {
            state.comps = allComps.map((item) => ({
                ...item,
                show: checkIsShow(item.comName),
                disabled: checkIsDisabled(item.comName)
            }));
        };
        const init = () => {
            getDetailData();
            instance.proxy.$mitt.on('updateVersionDetail', () => {
                getDetailData();
            });
        };
        const handleSave = async ({ query, type }) => {
            //校验
            let res = true;
            for (let i = 0; i < state.comps.length; i++) {
                const target = unref(compsItemRefs[state.comps[i].comName]);
                if (target?.validate) {
                    res = await target?.validate(query);
                }
                if (res) {
                    if (target?.form) {
                        state.form = {
                            ...state.form,
                            ...target.form
                        };
                    }
                } else {
                    return;
                }
            }
            if (type === 5) {
                state.loading = true;
            } else {
                state.progressLoading = true;
            }
            state.comps = state.comps.map((item) => ({
                ...item,
                disabled: true
            }));
            let pmpProductRequires = state.form.pmpProductRequires || [];
            if (state.form.pmpRequestInfos && state.form.pmpRequestInfos.length) {
                state.form.pmpRequestInfos.forEach((item) => {
                    item.pmpProductRequires = item.pmpProductRequires || [];
                    pmpProductRequires = pmpProductRequires.concat(item.pmpProductRequires);
                });
            }
            // 保存
            if (type === 5) {
                api.versionModel
                    .save({
                        ...state.detailData,
                        ...state.form,
                        pmpProductRequires
                    })
                    .then(({ success, errorMsg }) => {
                        if (success) {
                            message.success('操作成功');
                            state.loading = false;
                            state.showModal = false;
                        } else {
                            message.error(errorMsg);
                        }
                    });
            } else {
                setTimeout(() => {
                    // 生成pdf文件
                    let files: FileItem[] = [];
                    state.tip = '文件生成';
                    state.percent = 20;
                    instance.proxy.$getPdf(document.querySelector('#pdfDom') as any).then((data) => {
                        state.tip = '文件上传';
                        state.percent = 40;
                        let filename = `${state.title}.pdf`;
                        filename = filename.replace(/\//g, '');
                        const file = dataURLtoFile(data, filename);
                        const formData = new FormData();
                        formData.append('files', file);
                        api.fileModel.upload(formData).then(({ success, moule, errorMsg }) => {
                            state.tip = '保存中';
                            state.percent = 60;
                            if (success) {
                                files = [
                                    {
                                        connectType: stepStatusConnectType[state.processStepStatus],
                                        type: 1,
                                        status: 'add',
                                        userName: store.getters.userInfo.employeeDTO.name,
                                        uploadUser: store.getters.userInfo.employeeDTO.empId,
                                        ...moule[0]
                                    }
                                ];
                                let query = { ...state.detailData, ...state.form, pmpProductRequires };
                                query = {
                                    ...query,
                                    startRequest: '',
                                    acceptRequest: '',
                                    productDoc: '',
                                    requestDoc: '',
                                    purchaseUpdate: '',
                                    schedule: '',
                                    testReport: '',
                                    reviewRecord: '',
                                    acceptance: ''
                                };
                                query.pmpProductRequires.forEach((item, index) => {
                                    query.pmpProductRequires[index].verOpinion = '';
                                });
                                api.productProcessModel
                                    .auditProcess({
                                        ...query,
                                        files: [...state.form.files, ...files]
                                    })
                                    .then(({ success, errorMsg }) => {
                                        if (success) {
                                            state.tip = '保存成功';
                                            state.percent = 100;
                                            setTimeout(() => {
                                                state.progressLoading = false;
                                                message.success('操作成功');
                                                emit('success');
                                                state.showModal = false;
                                            }, 500);
                                        } else {
                                            state.progressLoading = false;
                                            message.error(errorMsg);
                                        }
                                    });
                            } else {
                                message.error(errorMsg);
                            }
                        });
                    });
                });
            }
        };
        onBeforeUnmount(() => {
            instance.proxy.$mitt.all.delete('updateVersionDetail');
        });
        return {
            ...toRefs(state),
            setCompsItemRef,
            empId,
            open,
            getDetailData,
            checkIsShow,
            detailChange,
            handleSave
        };
    }
});
</script>
<style lang="less" scoped >
.page-wrap {
    position: relative;
    height: 100%;
    .page-header-wrap {
        position: sticky;
        top: 0;
        z-index: 100;
        border-bottom: 1px solid #f1f1f1;
        border-top: 1px solid #f1f1f1;
        background: #fff;
        &::before {
            content: '';
            position: absolute;
            width: 6px;
            height: 100%;
            background: #fb7555;
            top: 0;
            left: 0;
            z-index: 120;
        }
    }
    .header-title {
        font-size: 20px;
        color: @title-font-color;
        font-weight: bold;
    }
    .page-cont {
        position: relative;
        margin-top: 24px;
        background: #fff;
    }
}
</style>